package ip.controller;
/***********************************************************************
 * Module:  LoginAdministratorController.java
 * Author:  mojsilo
 * Purpose: Defines the Class LoginAdministratorController
 ***********************************************************************/

import java.io.IOException;

import ip.command.LoginCommand;
import ip.dto.UserDTO;
import ip.exceptions.ApplicationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * @web.servlet
 * 	name="LoginAdministratorController"
 * @web.servlet-mapping
 * 	url-pattern="/control/LoginAdministrator"
 */
public class LoginAdministratorController extends HttpServlet
{

	private static final long serialVersionUID = -4757948266164178476L;
	private Logger logger = Logger.getLogger(this.getClass());

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{		
		try{			
			logger.info("doGet(...)");
			UserDTO userDTO = new UserDTO();
			userDTO.setUsername(request.getParameter("username"));
			userDTO.setPassword(request.getParameter("password"));
			userDTO.setRole("a");
			
			logger.debug("doGet(...) - userDTO: "+userDTO);
			
			LoginCommand loginCommand;
			loginCommand = new LoginCommand();
			loginCommand.setUserDTO(userDTO);
			loginCommand.init();
			loginCommand.execute();
			loginCommand.dispose();
			logger.debug("loginCommand.getUserDTO(): "+loginCommand.getUserDTO());
			if (loginCommand.getUserDTO()!= null){
				HttpSession session = request.getSession(true);
				session.setAttribute("administrator", loginCommand.getUserDTO());
				getServletContext().getRequestDispatcher("/WEB-INF/jsp/administrator/main.jsp").forward(request, response);
			}
			else response.sendRedirect(response.encodeRedirectURL("../index.jsp"));//greska obraditi

		}
		catch (ApplicationException e) {
			logger.error(e);
			request.setAttribute("error", e.getMessage());
			getServletConfig().getServletContext().getRequestDispatcher("error.jsp").forward(request, response);
		}
		catch (Exception e) {
			logger.error(e);
			request.setAttribute("error", "Unexpected error!!");//kako ovo bolje odraditi???
			getServletConfig().getServletContext().getRequestDispatcher("error.jsp").forward(request, response);
		}	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		logger.info("doPost(...)");
		doGet(request, response);
	}

}